package org.example.onlineEducation.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {

    //JWT失效时长：1小时
    private static final long JWT_TTL = 60 * 60 * 1000;
    //JWT加密盐：凡王之血，必以剑终
    private static final String JWT_KEY = "Every king's blood will end with a sword";

    public static String createToken(String id, String subject){
        SecretKey key = Keys.hmacShaKeyFor(JWT_KEY.getBytes(StandardCharsets.UTF_8));
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",id);
        JwtBuilder jwtBuilder = Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setExpiration(new Date(System.currentTimeMillis()+JWT_TTL))
                .signWith(key, SignatureAlgorithm.HS256);
        return jwtBuilder.compact();
    }

    public static Claims parseToken(String token){
        SecretKey key = Keys.hmacShaKeyFor(JWT_KEY.getBytes(StandardCharsets.UTF_8));
        return Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token).getBody();
    }
}
